<template>
  <div class="home container">
    <Alert v-if="alert" :message="alert" />
    <!-- 搜索 -->
    <input
      type="search"
      class="form-control"
      placeholder="输入姓名. . .（区分大小写）"
      v-model="filterInput"
    />
    <!-- 表格 -->
    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">姓名</th>
          <th scope="col">电话</th>
          <th scope="col">邮箱</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="customer in filterBy(customers, filterInput)"
          :key="customer.id"
        >
          <th scope="row">{{ customer.id }}</th>
          <td>{{ customer.name }}</td>
          <td>{{ customer.phone }}</td>
          <td>{{ customer.email }}</td>
          <td>
            <router-link :to="'/detail/' + customer.id">详情</router-link>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
import {
  ref,
  defineComponent,
  onMounted,
  onUpdated,
  onUnmounted,
  computed,
} from "vue";
import { useRoute } from "vue-router";
import axios from "axios";
import Alert from "@/components/Alert.vue";
import { Customer } from "@/utils/types.ts";

export default defineComponent({
  name: "Home",
  components: {
    Alert,
  },
  setup() {
    const route = useRoute();
    let customers = ref<[]>([]);
    const alert = ref<string>("");
    let timer = ref<any>("");
    let filterInput = ref<string>("");
    // console.log(route);
    // 判断路由参数中是否有此值
    if (route.query.alert) {
      alert.value = route.query.alert + "";

      timer = setTimeout(() => (alert.value = ""), 2000);
    }

    onMounted(async () => {
      let res = await axios.get(`http://localhost:3000/users`);
      customers.value = res.data;
    });

    onUnmounted(() => {
      clearTimeout(timer);
    });
    onUpdated(async () => {
      let res = await axios.get(`http://localhost:3000/users`);
      customers.value = res.data;
    });

    // 实现搜索
    const filterBy = (customers: Customer[], value: string) => {
      return customers.filter((customer: Customer) =>
        customer.name.match(value)
      );
    };
    // console.log(filterCustomers);

    return { customers, alert, filterInput, filterBy };
  },
});
</script>
